<template>
    <div class="address-form">
        <van-form @submit="values => $emit('submit', values)" ref="addressForm">
            <van-field :value="addressValue.id" name="id" class="address-form-hidden-field"/>
            <van-field :value="addressValue.provinceId" name="province_id" class="address-form-hidden-field"/>
            <van-field :value="addressValue.province" name="province" class="address-form-hidden-field"/>
            <van-field :value="addressValue.cityId" name="city_id" class="address-form-hidden-field"/>
            <van-field :value="addressValue.city" name="city" class="address-form-hidden-field"/>
            <van-field :value="addressValue.countyId" name="county_id" class="address-form-hidden-field"/>
            <van-field :value="addressValue.county" name="county" class="address-form-hidden-field"/>
            <van-field v-model="addressValue.lastName" name="last_name" label="收货人姓" placeholder="收货人姓"
                       :rules="[{ required: true, message: '请填写收货人姓' }]"/>
            <van-field v-model="addressValue.firstName" name="first_name" label="收货人名" placeholder="收货人名"
                       :rules="[{ required: true, message: '请填写收货人名' }]"/>
            <van-field v-model="addressValue.phone" name="phone" type="tel" label="手机号" placeholder="收货人手机号"
                       :rules="[{ pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '手机号格式不正确' }]"/>
            <van-field :value="location" name="location" label="所在地区" placeholder="选择省 / 市 / 区" is-link readonly
                       :rules="[{ required: true, message: '请选择所在地区' }]"
                       @click.stop="handleShowAddressPopup"/>
            <van-field v-model="addressValue.address" name="address" label="详细地址" placeholder="街道门牌、楼层房间号等信息"
                       :rules="[{ required: true, message: '请填写详细地址' }]"/>
            <van-field v-model="addressValue.zip" name="zip" label="邮政编码" :maxlength="6" placeholder="邮政编码"/>
            <white-space/>
            <van-cell title="设为默认收货地址" label="提醒: 每次下单默认推荐使用该地址" center value-class="address-defaulted-cell-value">
                <template #default>
                    <van-field name="defaulted" input-align="right">
                        <template #input>
                            <van-switch v-model="addressValue.defaulted" size="22px"/>
                        </template>
                    </van-field>
                </template>
            </van-cell>
        </van-form>
        <van-popup v-model="showAddressPopup" position="bottom">
            <van-area :area-list="area" :value="locationCode"
                      :loading="locationLoading"
                      @cancel="showAddressPopup = false"
                      @confirm="handleAddressConfirm"/>
        </van-popup>
        <div class="address-save-buttons van-hairline--top">
            <van-button type="primary" round block @load="loading"
                        @click.stop="$refs.addressForm.submit()">
                保存
            </van-button>
        </div>
    </div>
</template>

<script>
  import * as _ from "lodash"
  import { customer, district } from "@mall/api-services"
  import { Area, Button, Cell, Field, Form, Popup, Switch } from "vant"
  import WhiteSpace from "@/components/WhiteSpace"
  import area from "./area"

  const { DistrictService } = district

  export default {
    name: "AddressForm",
    components: {
      WhiteSpace,
      [Area.name]: Area,
      [Button.name]: Button,
      [Cell.name]: Cell,
      [Field.name]: Field,
      [Form.name]: Form,
      [Switch.name]: Switch,
      [Popup.name]: Popup,
    },
    props: {
      loading: Boolean,
      address: customer.CustomerAddress,
    },
    watch: {
      address(address) {
        this.addressValue = _.assign(new customer.CustomerAddress(), address)
      },
    },
    computed: {
      location() {
        const { addressValue } = this
        const { province, city, county } = addressValue
        const location = `${province}/${city}/${county}`
        return _.isEqual(location, "//") ? "" : location
      },
    },
    data() {
      return {
        area,
        showAddressPopup: false,
        locationLoading: false,
        locationCode: "",
        addressValue: new customer.CustomerAddress(),
      }
    },
    created() {
      this.addressValue = _.assign(new customer.CustomerAddress(), this.address)
    },
    methods: {
      refreshFetchAddress() {
        const { addressValue } = this
        const { countyId } = addressValue
        if (_.isEmpty(countyId) || !_.isEmpty(this.locationCode)) {
          return
        }
        this.locationLoading = true
        DistrictService.getCounty(countyId)
          .then(county => this.locationCode = county ? county.code : "")
          .finally(() => this.locationLoading = false)

      },
      handleAddressConfirm(values) {
        const [provinceValue, cityValue, countyValue] = values
        this.locationLoading = true
        DistrictService.getProvinces()
          .countryId("1")
          .list()
          .then(provinces => _.find(provinces, province => province.code === provinceValue.code))
          .then(province => new Promise((resolve, reject) => {
            if (_.isUndefined(province)) {
              reject("所选省份不存在")
            } else {
              this.addressValue.provinceId = province.id
              this.addressValue.province = province.name
              resolve(province.id)
            }
          }))
          .then(provinceId => DistrictService.getCities().provinceId(provinceId).scope(2).list())
          .then(cities => _.find(cities, city => city.code === cityValue.code))
          .then(city => new Promise((resolve, reject) => {
            if (_.isUndefined(city)) {
              reject("所选市不存在")
            } else {
              this.addressValue.cityId = city.id
              this.addressValue.city = city.name
              resolve(city.counties)
            }
          }))
          .then(counties => _.find(counties, county => county.code === countyValue.code))
          .then(county => new Promise((resolve, reject) => {
            if (_.isUndefined(county)) {
              reject("所选县不存在")
            } else {
              this.addressValue.countyId = county.id
              this.addressValue.county = county.name
              resolve()
            }
          }))
          .finally(() => this.locationLoading = false)
          .finally(() => this.showAddressPopup = false)

      },
      handleShowAddressPopup() {
        this.showAddressPopup = true
        this.refreshFetchAddress()
      },
    },
  }
</script>

<style lang="scss" scoped>

    .address-form {
        ::v-deep .van-field__label {
            flex: none;
            width: 70px;
        }
    }

    .address-defaulted-cell-value {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        flex: 0.5;

        .van-field {
            padding: 0;
        }
    }

    .address-form-hidden-field {
        display: none;
    }

    .address-save-buttons {
        padding: 10px 20px;
        position: fixed;
        bottom: 0;
        right: 0;
        left: 0;
        background: #fff;
    }
</style>
